package com.example.qincetest.ui.activity

import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import timber.log.Timber

class WebViewActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    WebViewScreen()
                }
            }
        }
    }
}

@Composable
fun WebViewScreen() {
    var webViewVersion by remember { mutableStateOf("") }
    val context = LocalContext.current

    LaunchedEffect(Unit) {
        // 获取 WebView 版本号
        val packageInfo = context.packageManager.getPackageInfo("com.google.android.webview", 0)
        webViewVersion = "WebView 版本: ${packageInfo.versionName}"
        Timber.d("WebView version: ${packageInfo.versionName}")
    }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        // 显示版本号
        Text(
            text = webViewVersion,
            modifier = Modifier.padding(16.dp),
            style = MaterialTheme.typography.bodyMedium
        )

        // WebView
        AndroidView(
            modifier = Modifier.weight(1f),
            factory = { context ->
                WebView(context).apply {
                    webViewClient = WebViewClient()
                    settings.apply {
                        javaScriptEnabled = true  // 启用 JavaScript
                        domStorageEnabled = true  // 启用 DOM storage API
                        // 设置缓存模式
                        cacheMode = android.webkit.WebSettings.LOAD_DEFAULT
                    }
                    loadUrl("https://liulanmi.com/labs/core.html")
                }
            },
            update = { webView ->
                // 如果需要更新 WebView，可以在这里处理
            }
        )
    }
} 